import { Provide, Inject } from '@midwayjs/core';
import puppeteer from 'puppeteer';
import { createHtml } from '../utils/htmlHelper';

const MAX_WSE = 4; //启动几个浏览器
const WSE_LIST = []; //存储browserWSEndpoint列表

const init = async () => {
  for (let i = 0; i < MAX_WSE; i++) {
    const browser = await puppeteer.launch({
      headless: true,
      defaultViewport: null, // 默认视窗大小，null表示自动设置
      ignoreHTTPSErrors: true, // 是否忽略HTTPS错误，默认为false
      args: ['single-process'],
    });
    const browserWSEndpoint = await browser.wsEndpoint();
    WSE_LIST[i] = browserWSEndpoint;
  }
};

init();
@Provide()
export class HtmlService {
  @Inject()
  logger;

  async hiprintToHtml(options: any) {
    const tmp = Math.floor(Math.random() * MAX_WSE);
    const browserWSEndpoint = WSE_LIST[tmp];
    const browser = await puppeteer.connect({ browserWSEndpoint });
    const page = await browser.newPage();
    await page.goto(
      `http://localhost:7001/public/print-web/index.html/#/createHiprintHtml?id=${options.id}`,
      {
        waitUntil: 'networkidle2',
      }
    );
    // await page.screenshot({
    //   path: 'test.png',
    //   fullPage: true,
    // });
    this.logger.info('puppeteer页面打开成功');
    await page.waitForSelector('#print-cont');
    const html = await page.$eval('#print-cont', el => el.innerHTML);
    this.logger.info('puppeteer页面#print-cont数据获取成功');
    await page.close();
    const fullHtml = createHtml(html);
    return fullHtml;
  }
}
